package com.websocket.web.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint(value = "/chat1/{userName}/{token}")
@Component
public class Chat1WebSocket {
    // session缓存
    Map<String, Session> sessionMap = new HashMap<>();

    public Chat1WebSocket() {
        System.out.println("载入 Chat1WebSocket 构造方法");
    }

    @OnOpen
    public void openConn(Session session, @PathParam("userName") String userName, @PathParam("token") String token) {
        String sessionId = session.getId();
        System.out.println("建立ws连接: " + sessionId);
        sessionMap.put(sessionId, session);
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        String sessionId = session.getId();
        String reasonPhrase = reason.getReasonPhrase();
        System.out.println(String.format("关闭ws连接: %s, reason: %s", sessionId, reasonPhrase));
        sessionMap.remove(sessionId);
    }

    @OnMessage
    public void echoTextMessage(Session session, String msg, boolean last) {
        if (session.isOpen()) {
            System.out.println("收到ws消息 = " + msg);
            // 给所有ws客户端广播消息
        }
    }
    /*
    html 客户端代码:
    var wsClient = new WebSocket('ws://localhost:8080/chat1/zhangsan/99999')
    wsClient.send('你好吗?')
    wsClient.close()
     */

}
